#include<iostream>
#include<vector>
#include<algorithm>

using namespace std;
int threeSumClosest(vector<int>& nums, int target) {
    sort(nums.begin(), nums.end()); // 升序
    int start, end;
    int tmp = nums[0] + nums[1] + nums[2];
    for (int i = 0; i < nums.size(); i++) {
        start = i + 1;
        end = nums.size() - 1;
        while(start < end) {
            int sum = nums[i] + nums[start] + nums[end];
            if (abs(sum - target) < abs(tmp - target)) {
                tmp = sum;
            }
            if (sum > target) {
                end--;
            } else if (sum < target) {
                start++;
            } else if (sum == target) {
                return tmp;
            } else {
                cout << "ERROR" << endl;
            }
        }
    }
    return tmp;

}
int main() {
    vector<int> nums = {-1,2,1,-4};
    int target = 1;
    int res = threeSumClosest(nums, target);
    cout << res << endl;

}